package com.demo.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SetCookieServlet extends HttpServlet {
	
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		PrintWriter out = response.getWriter();
		
		//给客户端电脑种点cookie
		Cookie cookie1 = new Cookie("country","USA"); //名值对
		Cookie cookie2 = new Cookie("dish","youtiao");
		//cookie1.setDomain("taobaoabc.com");//只有自己域名的应用才能访问自己的cookie
		cookie1.setPath("/");//代表自己网站的某个路径可以访问cookie
		cookie1.setMaxAge(10*60);//设置cookie的存活期，单位秒。想永久存储就设置时间，否则不设置或者设为负数 零，浏览器关闭就没了


		response.addCookie(cookie1);//种cookie
		response.addCookie(cookie2);

		//获取客户端所有cookie的办法
		Cookie[] cookies = request.getCookies();
		if(cookies!=null) {
			if(cookies.length>0) {
				for(Cookie c: cookies){
					if(c.getName().equals("a")){
						c.setMaxAge(-1);//设为负数，代表浏览器关闭cookie就失效。设为0也会退出时删除
						//c.setValue("");
					}
					out.print(c.getName()+"-"+c.getValue()+"<br/>");
				}
			}
		}
		
		
	}

}
